{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "intro_to_fairness.ipynb",
      "version": "0.3.2",
      "provenance": [],
      "collapsed_sections": [
        "KlF-lQ8yQ69b",
        "qZ-9vJgSEpHj",
        "TF3B5h3c-7Fb"
      ]
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "cells": [
    {
      "metadata": {
        "id": "naMQPO5iRpNE",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "#### Copyright 2018 Google LLC."
      ]
    },
    {
      "metadata": {
        "id": "sHpbnneJYcwJ",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "84x4Fxc5lzFv",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "# Intro to ML Fairness\n",
        "***"
      ]
    },
    {
      "metadata": {
        "id": "J8daw3YOIAXH",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Disclaimer\n",
        "This exercise explores just a small subset of  ideas and techniques relevant to fairness in machine learning; it is not the whole story!"
      ]
    },
    {
      "metadata": {
        "id": "xFxZOg55lWJE",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Learning Objectives\n",
        "\n",
        "* Increase awareness of different types of biases that can manifest in model data.\n",
        "* Explore feature data to proactively identify potential sources of bias before training a model\n",
        "* Evaluate model performace by subgroup rather than in aggregate"
      ]
    },
    {
      "metadata": {
        "id": "l-K-xqksm-X3",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Overview\n",
        "\n",
        "In this exercise, you'll explore datasets and evaluate classifiers with *fairness* in mind, noting the ways undesirable biases can creep into machine learning (ML).\n",
        "\n",
        "Throughout, you will see **FairAware** tasks, which provide opportunities to contextualize ML processes with respect to fairness. In performing these tasks, you'll identify biases and consider the long-term impact of model predictions if these biases are not addressed."
      ]
    },
    {
      "metadata": {
        "id": "TXkkHYyJ98_k",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## About the Dataset and Prediction Task\n",
        "\n",
        "In this exercise, you'll work with the [Adult Census Income dataset](https://archive.ics.uci.edu/ml/datasets/Census+Income), which is commonly used in machine learning literature. This data was extracted from the [1994 Census bureau database](http://www.census.gov/en.html) by Ronny Kohavi and Barry Becker.\n",
        "\n",
        "Each example in the dataset contains the following demographic data for a set of individuals who took part in the 1994 Census:\n",
        "\n",
        "### Numeric Features\n",
        "*   `age`: The age of the individual in years.\n",
        "*   `fnlwgt`: The number of individuals the Census Organizations believes that set of observations represents.\n",
        "*   `education_num`:  An enumeration of the categorical representation of education. The higher the number, the higher the education that individual achieved. For example, an `education_num` of `11` represents `Assoc_voc` (associate degree at a vocational school), an `education_num` of `13` represents `Bachelors`, and an `education_num` of `9` represents `HS-grad` (high school graduate).\n",
        "*   `capital_gain`: Capital gain made by the individual, represented in US Dollars.\n",
        "*   `capital_loss`: Capital loss mabe by the individual, represented in US Dollars.\n",
        "*   `hours_per_week`: Hours worked per week.\n",
        "\n",
        "### Categorical Features\n",
        "*   `workclass`: The individual's type of employer. Examples include: `Private`, `Self-emp-not-inc`, `Self-emp-inc`, `Federal-gov`, `Local-gov`, `State-gov`, `Without-pay`, and `Never-worked`.\n",
        "*   `education`: The highest level of education achieved for that individual.\n",
        "*   `marital_status`: Marital status of the individual. Examples include: `Married-civ-spouse`, `Divorced`, `Never-married`, `Separated`, `Widowed`, `Married-spouse-absent`, and `Married-AF-spouse`.\n",
        "*   `occupation`: The occupation of the individual. Example include: `tech-support`, `Craft-repair`, `Other-service`, `Sales`, `Exec-managerial` and more.\n",
        "*   `relationship`:  The relationship of each individual in a household. Examples include: `Wife`, `Own-child`, `Husband`, `Not-in-family`, `Other-relative`, and `Unmarried`.\n",
        "*   `gender`:  Gender of the individual available only in binary choices: `Female` or `Male`.\n",
        "*   `race`: `White`, `Asian-Pac-Islander`, `Amer-Indian-Eskimo`, `Black`, and `Other`. \n",
        "*   `native_country`: Country of origin of the individual. Examples include: `United-States`, `Cambodia`, `England`, `Puerto-Rico`, `Canada`, `Germany`, `Outlying-US(Guam-USVI-etc)`, `India`, `Japan`, `United-States`, `Cambodia`, `England`, `Puerto-Rico`, `Canada`, `Germany`, `Outlying-US(Guam-USVI-etc)`, `India`, `Japan`, and more.\n",
        "\n",
        "### Prediction Task\n",
        "The prediction task is to **determine whether a person makes over $50,000 US Dollar a year.**\n",
        "\n",
        "### Label\n",
        "*   `income_bracket`: Whether the person makes more than $50,000 US Dollars annually.\n",
        "\n",
        "### Notes on Data Collection\n",
        "\n",
        "All the examples extracted for this dataset meet the following conditions: \n",
        "*   `age` is 16 years or older.\n",
        "*   The adjusted gross income (used to calculate `income_bracket`) is greater than $100 USD annually.\n",
        "*   `fnlwgt` is greater than 0.\n",
        "*   `hours_per_week` is greater than 0.\n",
        "\n",
        "\n",
        "\n",
        "\n"
      ]
    },
    {
      "metadata": {
        "id": "I0RMIktKy8xX",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Setup\n",
        "\n",
        "First, import some modules that will be used throughout this notebook."
      ]
    },
    {
      "metadata": {
        "id": "2e_0DJJ8zE29",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "import os\n",
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "import pandas as pd\n",
        "import tensorflow as tf\n",
        "import tempfile\n",
        "!pip install seaborn==0.8.1\n",
        "import seaborn as sns\n",
        "import itertools\n",
        "from sklearn.metrics import confusion_matrix\n",
        "from sklearn.metrics import roc_curve, roc_auc_score\n",
        "from sklearn.metrics import precision_recall_curve\n",
        "from google.colab import widgets\n",
        "# For facets\n",
        "from IPython.core.display import display, HTML\n",
        "import base64\n",
        "!pip install facets-overview==1.0.0\n",
        "from facets_overview.feature_statistics_generator import FeatureStatisticsGenerator\n",
        "\n",
        "print('Modules are imported.')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "-xgIRapb5LaQ",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Load the Adult Dataset\n",
        "\n",
        "With the modules now imported, we can load the Adult dataset into a pandas DataFrame data structure."
      ]
    },
    {
      "metadata": {
        "id": "TeCNVvVUVS0P",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "COLUMNS = [\"age\", \"workclass\", \"fnlwgt\", \"education\", \"education_num\",\n",
        "           \"marital_status\", \"occupation\", \"relationship\", \"race\", \"gender\",\n",
        "           \"capital_gain\", \"capital_loss\", \"hours_per_week\", \"native_country\",\n",
        "           \"income_bracket\"]\n",
        "\n",
        "train_df = pd.read_csv(\n",
        "    \"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data\",\n",
        "    names=COLUMNS,\n",
        "    sep=r'\\s*,\\s*',\n",
        "    engine='python',\n",
        "    na_values=\"?\")\n",
        "test_df = pd.read_csv(\n",
        "    \"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test\",\n",
        "    names=COLUMNS,\n",
        "    sep=r'\\s*,\\s*',\n",
        "    skiprows=[0],\n",
        "    engine='python',\n",
        "    na_values=\"?\")\n",
        "\n",
        "# Drop rows with missing values\n",
        "train_df = train_df.dropna(how=\"any\", axis=0)\n",
        "test_df = test_df.dropna(how=\"any\", axis=0)\n",
        "\n",
        "print('UCI Adult Census Income dataset loaded.')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "coilRN-hooja",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Analyzing the Adult Dataset with Facets\n",
        "\n",
        "As mentioned in MLCC, it is important to understand your dataset *before* diving straight into the prediction task. \n",
        "\n",
        "Some important questions to investigate when auditing a dataset for fairness:\n",
        "\n",
        "* **Are there missing feature values for a large number of observations?**\n",
        "* **Are there features that are missing that might affect other features?**\n",
        "* **Are there any unexpected feature values?**\n",
        "* **What signs of data skew do you see?**"
      ]
    },
    {
      "metadata": {
        "id": "9yCIuAqWA1Pm",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "To start, we can use [Facets Overview](https://pair-code.github.io/facets/), an interactive visualization tool that can help us explore the dataset. With Facets Overview, we can quickly analyze the distribution of values across the Adult dataset."
      ]
    },
    {
      "metadata": {
        "id": "MW-qryqs1gig",
        "colab_type": "code",
        "cellView": "form",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "#@title Visualize the Data in Facets\n",
        "fsg = FeatureStatisticsGenerator()\n",
        "dataframes = [\n",
        "    {'table': train_df, 'name': 'trainData'}]\n",
        "censusProto = fsg.ProtoFromDataFrames(dataframes)\n",
        "protostr = base64.b64encode(censusProto.SerializeToString()).decode(\"utf-8\")\n",
        "\n",
        "\n",
        "HTML_TEMPLATE = \"\"\"<script src=\"https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/1.3.3/webcomponents-lite.js\"></script>\n",
	"        <link rel=\"import\" href=\"https://raw.githubusercontent.com/PAIR-code/facets/1.0.0/facets-dist/facets-jupyter.html\">\n",
        "        <facets-overview id=\"elem\"></facets-overview>\n",
        "        <script>\n",
        "          document.querySelector(\"#elem\").protoInput = \"{protostr}\";\n",
        "        </script>\"\"\"\n",
        "html = HTML_TEMPLATE.format(protostr=protostr)\n",
        "display(HTML(html))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "91wjnZFpPWw-",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### FairAware Task #1\n",
        "\n",
        "Review the descriptive statistics and histograms for each numerical and continuous feature. Click the **Show Raw Data** button above the histograms for categorical features to see the distribution of values per category.\n",
        "\n",
        "Then, try to answer the following questions from earlier:\n",
        "\n",
        "1. Are there missing feature values for a large number of observations?\n",
        "2. Are there features that are missing that might affect other features?\n",
        "3. Are there any unexpected feature values?\n",
        "4. What signs of data skew do you see?"
      ]
    },
    {
      "metadata": {
        "id": "KlF-lQ8yQ69b",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Solution\n",
        "\n",
        "Click below for some insights we uncovered."
      ]
    },
    {
      "metadata": {
        "id": "xX_qjj5AQ_Hb",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "We can see from reviewing the **missing** columns for both numeric and categorical features that there are no missing feature values, so that is not a concern here. \n",
        "\n",
        "By looking at the min/max values and histograms for each numeric feature, we can pinpoint any extreme outliers in our data set. For `hours_per_week`, we can see that the minimum is 1, which might be a bit surprising, given that most jobs typically require multiple hours of work per week. For `capital_gain` and `capital_loss`, we can see that over 90% of values are 0. Given that capital gains/losses are only registered by individuals who make investments, it's certainly plausible that less than 10% of examples would have nonzero values for these feature, but we may want to take a closer look to verify the values for these features are valid.\n",
        "\n",
        "In looking at the histogram for gender, we see that over two-thirds (approximately 67%) of examples represent males. This strongly suggests data skew, as we would expect the breakdown between genders to be closer to 50/50."
      ]
    },
    {
      "metadata": {
        "id": "hKj2hz-Sql7V",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### A Deeper Dive\n",
        "\n",
        "To futher explore the dataset, we can use [Facets Dive](https://pair-code.github.io/facets/), a tool that provides an interactive interface where each individual item in the visualization represents a data point. But to use Facets Dive, we need to convert our data to a JSON array.\n",
        "Thankfully the DataFrame method `to_json()` takes care of this for us.\n",
        "\n",
        "Run the cell below to perform the data transform to JSON and also load Facets Dive. "
      ]
    },
    {
      "metadata": {
        "id": "stlklrG_xssF",
        "colab_type": "code",
        "cellView": "form",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "#@title Set the Number of Data Points to Visualize in Facets Dive\n",
        "\n",
        "SAMPLE_SIZE = 2500 #@param\n",
        "  \n",
        "train_dive = train_df.sample(SAMPLE_SIZE).to_json(orient='records')\n",
        "\n",
        "HTML_TEMPLATE = \"\"\"<script src=\"https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/1.3.3/webcomponents-lite.js\"></script>\n",
        "        <link rel=\"import\" href=\"https://raw.githubusercontent.com/PAIR-code/facets/1.0.0/facets-dist/facets-jupyter.html\">\n",
        "        <facets-dive id=\"elem\" height=\"600\"></facets-dive>\n",
        "        <script>\n",
        "          var data = {jsonstr};\n",
        "          document.querySelector(\"#elem\").data = data;\n",
        "        </script>\"\"\"\n",
        "html = HTML_TEMPLATE.format(jsonstr=train_dive)\n",
        "display(HTML(html))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "LxqAPDcRDFB2",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## FairAware Task #2\n",
        "\n",
        "Use the menus on the left panel of the visualization to change how the data is organized:\n",
        "\n",
        "1. In the **Faceting | X-Axis** menu, select **education**, and in the **Display | Color** and  **Display | Type** menus, select **income_bracket**. How would you describe the relationship between education level and income bracket?\n",
        "\n",
        "2. Next, in the **Faceting | X-Axis** menu, select  **marital_status**, and in the **Display | Color** and  **Display | Type** menus, select **gender**. What noteworthy observations can you make about the gender distributions for each marital-status category?\n",
        "\n",
        "As you perform the above tasks, keep the following fairness-related questions in mind:\n",
        "\n",
        "*  **What's missing?**\n",
        "* **What's being overgeneralized?**\n",
        "* **What's being underrepresented?**\n",
        "* **How do the variables, and their values, reflect the real world?**\n",
        "* **What might we be leaving out?**"
      ]
    },
    {
      "metadata": {
        "id": "qZ-9vJgSEpHj",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Solution\n",
        "\n",
        "Click below for some insights we uncovered."
      ]
    },
    {
      "metadata": {
        "id": "uYpbgdATEx8L",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "1. In our data set, higher education levels generally tend to correlate with a higher income bracket. An income level of greater than $50,000 is more heavily represented in examples where education level is Bachelor's degree or higher.\n",
        "\n",
        "2. In most marital-status categories, the distribution of male vs. female values is close to 1:1. The one notable exception is \"married-civ-spouse\", where male outnumbers female by more than 5:1. Given that we already discovered in Task #1 that there is a disproportionately high representation of men in our data set, we can now infer that it's married women specifically that are underrepresented in our data."
      ]
    },
    {
      "metadata": {
        "id": "7YVH8hYfSjer",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Summary\n",
        "\n",
        "Plotting histograms, ranking most-to-least common examples, identifying duplicate or missing examples, making sure the training and test sets are similar, computing feature quantiles—**these are all critical analyses to perform on your data.** \n",
        "\n",
        "**The better you know what's going on in your data, the more insight you'll have as to where unfairness might creep in!**"
      ]
    },
    {
      "metadata": {
        "id": "2ivWw9Wpj67m",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### FairAware Task #3\n",
        "\n",
        "Now that you've explored the dataset using Facets, see if you can identify some of the problems that may arise with regard to fairness based on what you've learned about its features.\n",
        "\n",
        "Which of the following features might pose a problem with regard to fairness?\n",
        "\n",
        "Choose a feature from the drop-down options in the cell below, and then run the cell to check your answer. Then explore the rest of the options to get more insight about how each influences the model's predictions."
      ]
    },
    {
      "metadata": {
        "id": "8bFDVCV1sxiX",
        "colab_type": "code",
        "cellView": "form",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "feature = 'capital_gain / capital_loss' #@param [\"\", \"hours_per_week\", \"fnlwgt\", \"gender\", \"capital_gain / capital_loss\", \"age\"] {allow-input: false}\n",
        "\n",
        "\n",
        "if feature == \"hours_per_week\":\n",
        "  print(\n",
        "'''It does seem a little strange to see 'hours_per_week' max out at 99 hours,\n",
        "which could lead to data misrepresentation. One way to address this is by\n",
        "representing 'hours_per_week' as a binary \"working 40 hours/not working 40\n",
        "hours\" feature. Also keep in mind that data was extracted based on work hours\n",
        "being greater than 0. In other words, this feature representation exclude a\n",
        "subpopulation of the US that is not working. This could skew the outcomes of the\n",
        "model.''')\n",
        "if feature == \"fnlwgt\":\n",
        "  print(\n",
        "\"\"\"'fnlwgt' represents the weight of the observations. After fitting the model\n",
        "to this data set, if certain group of individuals end up performing poorly \n",
        "compared to other groups, then we could explore ways of reweighting each data \n",
        "point using this feature.\"\"\")\n",
        "if feature == \"gender\":\n",
        "  print(\n",
        "\"\"\"Looking at the ratio between men and women shows how disproportionate the data\n",
        "is compared to the real world where the ratio (at least in the US) is closer to\n",
        "1:1. This could pose a huge probem in performance across gender. Considerable\n",
        "measures may need to be taken to upsample the underrepresented group (in this\n",
        "case, women).\"\"\")\n",
        "if feature == \"capital_gain / capital_loss\":\n",
        "  print(\n",
        "\"\"\"Both 'capital_gain' and 'capital_loss' have very low variance, which might\n",
        "suggest they don't contribute a whole lot of information for predicting income. It\n",
        "may be okay to omit these features rather than giving the model more noise.\"\"\")\n",
        "if feature == \"age\":\n",
        "  print(\n",
        "'''\"age\" has a lot of variance, so it might benefit from bucketing to learn\n",
        "fine-grained correlations between income and age, as well as to prevent\n",
        "overfitting.''')\n"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "n3OT-YVpftEI",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Prediction Using TensorFlow Estimators\n",
        "\n",
        "Now that we have a better sense of the Adult dataset, we can now begin with creating a neural network to predict income. In this section, we will be using TensorFlow's Estimator API to access the `DNNClassifier` class"
      ]
    },
    {
      "metadata": {
        "id": "ECBRATBVG4rn",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Convert Adult Dataset into Tensors\n",
        "We first have to define our input fuction, which will take the Adult dataset that is in a pandas DataFrame and converts it into tensors using the ```tf.estimator.inputs.pandas_input_fn()``` function."
      ]
    },
    {
      "metadata": {
        "id": "Bt-rQvJLx4Hm",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "def csv_to_pandas_input_fn(data, batch_size=100, num_epochs=1, shuffle=False):\n",
        "  return tf.estimator.inputs.pandas_input_fn(\n",
        "      x=data.drop('income_bracket', axis=1),\n",
        "      y=data['income_bracket'].apply(lambda x: \">50K\" in x).astype(int),\n",
        "      batch_size=batch_size,\n",
        "      num_epochs=num_epochs,\n",
        "      shuffle=shuffle,\n",
        "      num_threads=1)\n",
        "\n",
        "print('csv_to_pandas_input_fn() defined.')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "0mz2sts6IjBO",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Represent Features in TensorFlow\n",
        "TensorFlow requires that data maps to a model. To accomplish this, you have to use ```tf.feature_columns``` to ingest and represent features in TensorFlow."
      ]
    },
    {
      "metadata": {
        "id": "tAG5hUJwx725",
        "colab_type": "code",
        "cellView": "form",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "#@title Categorical Feature Columns\n",
        "\n",
        "# Since we don't know the full range of possible values with occupation and\n",
        "# native_country, we'll use categorical_column_with_hash_bucket() to help map\n",
        "# each feature string into an integer ID.\n",
        "occupation = tf.feature_column.categorical_column_with_hash_bucket(\n",
        "    \"occupation\", hash_bucket_size=1000)\n",
        "native_country = tf.feature_column.categorical_column_with_hash_bucket(\n",
        "    \"native_country\", hash_bucket_size=1000)\n",
        "\n",
        "# For the remaining categorical features, since we know what the possible values\n",
        "# are, we can be more explicit and use categorical_column_with_vocabulary_list()\n",
        "gender = tf.feature_column.categorical_column_with_vocabulary_list(\n",
        "    \"gender\", [\"Female\", \"Male\"])\n",
        "race = tf.feature_column.categorical_column_with_vocabulary_list(\n",
        "    \"race\", [\n",
        "        \"White\", \"Asian-Pac-Islander\", \"Amer-Indian-Eskimo\", \"Other\", \"Black\"\n",
        "    ])\n",
        "education = tf.feature_column.categorical_column_with_vocabulary_list(\n",
        "    \"education\", [\n",
        "        \"Bachelors\", \"HS-grad\", \"11th\", \"Masters\", \"9th\",\n",
        "        \"Some-college\", \"Assoc-acdm\", \"Assoc-voc\", \"7th-8th\",\n",
        "        \"Doctorate\", \"Prof-school\", \"5th-6th\", \"10th\", \"1st-4th\",\n",
        "        \"Preschool\", \"12th\"\n",
        "    ])\n",
        "marital_status = tf.feature_column.categorical_column_with_vocabulary_list(\n",
        "    \"marital_status\", [\n",
        "        \"Married-civ-spouse\", \"Divorced\", \"Married-spouse-absent\",\n",
        "        \"Never-married\", \"Separated\", \"Married-AF-spouse\", \"Widowed\"\n",
        "    ])\n",
        "relationship = tf.feature_column.categorical_column_with_vocabulary_list(\n",
        "    \"relationship\", [\n",
        "        \"Husband\", \"Not-in-family\", \"Wife\", \"Own-child\", \"Unmarried\",\n",
        "        \"Other-relative\"\n",
        "    ])\n",
        "workclass = tf.feature_column.categorical_column_with_vocabulary_list(\n",
        "    \"workclass\", [\n",
        "        \"Self-emp-not-inc\", \"Private\", \"State-gov\", \"Federal-gov\",\n",
        "        \"Local-gov\", \"?\", \"Self-emp-inc\", \"Without-pay\", \"Never-worked\"\n",
        "    ])\n",
        "\n",
        "print('Categorical feature columns defined.')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "Jwtuu8MmyKCJ",
        "colab_type": "code",
        "cellView": "form",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "#@title Numeric Feature Columns\n",
        "# For Numeric features, we can just call on feature_column.numeric_column()\n",
        "# to use its raw value instead of having to create a map between value and ID.\n",
        "age = tf.feature_column.numeric_column(\"age\")\n",
        "fnlwgt = tf.feature_column.numeric_column(\"fnlwgt\")\n",
        "education_num = tf.feature_column.numeric_column(\"education_num\")\n",
        "capital_gain = tf.feature_column.numeric_column(\"capital_gain\")\n",
        "capital_loss = tf.feature_column.numeric_column(\"capital_loss\")\n",
        "hours_per_week = tf.feature_column.numeric_column(\"hours_per_week\")\n",
        "\n",
        "print('Numeric feature columns defined.')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "3WqAbug6jePb",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "#### Make Age a Categorical Feature\n",
        "\n",
        "If you chose `age` when completing **FairAware Task #3**, you noticed that we suggested that `age` might benefit from *bucketing* (also known as *binning*), grouping together similar ages into different groups. This might help the model generalize better across age. As such, we will convert `age` from a numeric feature (technically, an [ordinal feature](https://en.wikipedia.org/wiki/Ordinal_data)) to a categorical feature."
      ]
    },
    {
      "metadata": {
        "id": "HxVm8X15yLR7",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "age_buckets = tf.feature_column.bucketized_column(\n",
        "    age, boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65])"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "2lx4JuLdi7jw",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "#### Consider Key Subgroups\n",
        "\n",
        "When performing feature engineering, it's important to keep in mind that you may be working with data drawn from individuals belonging to subgroups, for which you'll want to evaluate model performance separately.\n",
        "\n",
        "**_NOTE:_** *In this context, a subgroup is defined as a group of individuals who share a given characteristic—such as race, gender, or sexual orientation—that merits special consideration when evaluating a model with fairness in mind.*\n",
        "\n",
        "When we want our models to mitigate, or leverage, the learned signal of a characteristic pertaining to a subgroup, we will want to use different kinds of tools and techniques—**most of which are still open research at this point**.\n",
        "\n",
        "As you work with different variables and define tasks for them, it can be useful to think about what comes next. For example, *where are the places where the interaction of the variable and the task could be a concern?*"
      ]
    },
    {
      "metadata": {
        "id": "5aD1OM8egad9",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Define the Model Features\n",
        "\n",
        "Now we can explicitly define which feature we will include in our model.\n",
        "\n",
        "We'll consider `gender` a subgroup and save it in a separate `subgroup_variables` list, so we can add special handling for it as needed."
      ]
    },
    {
      "metadata": {
        "id": "O68xV_24gbnD",
        "colab_type": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "# List of variables, with special handling for gender subgroup.\n",
        "variables = [native_country, education, occupation, workclass,\n",
        "             relationship, age_buckets]\n",
        "subgroup_variables = [gender]\n",
        "feature_columns = variables + subgroup_variables"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "3nYSMg67jWaA",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Train a Deep Neural Net Model on Adult Dataset"
      ]
    },
    {
      "metadata": {
        "id": "_kRL5rScH1F7",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "With the features now ready to go, we can try predicting income using deep learning.\n",
        "\n",
        "For the sake of simplicity, we are going to keep the neural network architecture light by simply **defining a feed-forward neural network with two hidden layers**.\n",
        "\n",
        "But first, we have to convert our high-dimensional categorical features into a low-dimensional and dense real-valued vector, which we call an embedding vector. Luckily, ```indicator_column``` (think of it as one-hot encoding) and ```embedding_column``` (that converts sparse features into dense features) helps us streamline the process.\n",
        "\n",
        "The following cell creates the deep columns needed to move forward with defining the model."
      ]
    },
    {
      "metadata": {
        "id": "bnyw4cyLTSUB",
        "colab_type": "code",
        "cellView": "code",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "deep_columns = [\n",
        "    tf.feature_column.indicator_column(workclass),\n",
        "    tf.feature_column.indicator_column(education),\n",
        "    tf.feature_column.indicator_column(age_buckets),\n",
        "    tf.feature_column.indicator_column(gender),\n",
        "    tf.feature_column.indicator_column(relationship),\n",
        "    tf.feature_column.embedding_column(native_country, dimension=8),\n",
        "    tf.feature_column.embedding_column(occupation, dimension=8),\n",
        "]\n",
        "\n",
        "print(deep_columns)\n",
        "print('Deep columns created.')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "lBaCn_Z1PshC",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "With all our data preprocessing taken care of, we can now define the deep neural net model. Start by using the parameters defined below. (Later on, after you've defined evaluation metrics and evaluated the model, you can come back and tweak these parameters to compare results.)\n",
        "\n"
      ]
    },
    {
      "metadata": {
        "id": "tQZ1kumWk8XO",
        "colab_type": "code",
        "cellView": "form",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "#@title Define Deep Neural Net Model\n",
        "\n",
        "HIDDEN_UNITS = [1024, 512] #@param\n",
        "LEARNING_RATE = 0.1 #@param\n",
        "L1_REGULARIZATION_STRENGTH = 0.0001 #@param\n",
        "L2_REGULARIZATION_STRENGTH = 0.0001 #@param\n",
        "\n",
        "model_dir = tempfile.mkdtemp()\n",
        "single_task_deep_model = tf.estimator.DNNClassifier(\n",
        "    feature_columns=deep_columns,\n",
        "    hidden_units=HIDDEN_UNITS,\n",
        "    optimizer=tf.train.ProximalAdagradOptimizer(\n",
        "      learning_rate=LEARNING_RATE,\n",
        "      l1_regularization_strength=L1_REGULARIZATION_STRENGTH,\n",
        "      l2_regularization_strength=L2_REGULARIZATION_STRENGTH),\n",
        "    model_dir=model_dir)\n",
        "\n",
        "print('Deep neural net model defined.')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "Tjhqo9XOP2VV",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "To keep things simple, we will train for 1000 steps—but feel free to play around with this parameter."
      ]
    },
    {
      "metadata": {
        "id": "UtrhAXwvqtVD",
        "colab_type": "code",
        "cellView": "form",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "#@title Fit Deep Neural Net Model to the Adult Training Dataset\n",
        "\n",
        "STEPS = 1000 #@param\n",
        "\n",
        "single_task_deep_model.train(\n",
        "    input_fn=csv_to_pandas_input_fn(train_df, num_epochs=None, shuffle=True),\n",
        "    steps=STEPS);\n",
        "\n",
        "print('Deep neural net model is done fitting.')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "m0UHu5t-P7G7",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "We can now evalute the overall model's performance using the held-out test set."
      ]
    },
    {
      "metadata": {
        "id": "HDV8hYqvncCy",
        "colab_type": "code",
        "cellView": "form",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "#@title Evaluate Deep Neural Net Performance\n",
        "\n",
        "results = single_task_deep_model.evaluate(\n",
        "    input_fn=csv_to_pandas_input_fn(test_df, num_epochs=1, shuffle=False),\n",
        "    steps=None)\n",
        "print(\"model directory = %s\" % model_dir)\n",
        "print(\"---- Results ----\")\n",
        "for key in sorted(results):\n",
        "  print(\"%s: %s\" % (key, results[key]))"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "7j0LrXMGlTDl",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "You can try retraining the model using different parameters. In the end, you will find that  a deep neural net does a decent job in predicting income. \n",
        "\n",
        "**But what is missing here is evaluation metrics with respect to subgroups.** We will cover some of the ways you can evaluate at the subgroup level in the next section."
      ]
    },
    {
      "metadata": {
        "id": "sbwmbnUUU1kY",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "## Evaluating for Fairness Using a Confusion Matrix\n",
        "\n",
        "While evaluating the overall performance of the model gives us some insight into its quality, it doesn't give us much insight into how well our model performs for different subgroups.  \n",
        "\n",
        "When evaluating a model for fairness, it's important to determine whether prediction errors are uniform across subgroups or whether certain subgroups are more susceptible to certain prediction errors than others. \n",
        "\n",
        "A key tool for comparing the prevalence of different types of model errors is a *confusion matrix*. Recall from the [Classification module of Machine Learning Crash Course](https://developers.google.com/machine-learning/crash-course/classification/true-false-positive-negative) that a confusion matrix is a grid that plots predictions vs. ground truth for your model, and tabulates statistics summarizing how often your model made the correct prediction and how often it made the wrong prediction. \n",
        "\n",
        "Let's start by creating a binary confusion matrix for our income-prediction model—binary because our label (`income_bracket`) has only two possible values (`<50K` or `>50K`). We'll define an income of `>50K` as our **positive label**, and an income of `<50k` as our **negative label**.\n",
        "\n",
        "**NOTE:** *Positive* and *negative* in this context should not be interpreted as value judgments (we are not suggesting that someone who earns more than 50k a year is a better person than someone who earns less than 50k). They are just standard terms used to distinguish between the two possible predictions the model can make.\n",
        "\n",
        "Cases where the model makes the correct prediction (the prediction matches the ground truth) are classified as **true**, and cases where the model makes the wrong prediction are classified as **false**.\n",
        "\n",
        "Our confusion matrix thus represents four possible states:\n",
        "\n",
        "* **true positive**: Model predicts `>50K`, and that is the ground truth.\n",
        "* **true negative**: Model predicts `<50K`, and that is the ground truth.\n",
        "* **false positive**: Model predicts `>50K`, and that contradicts reality.\n",
        "* **false negative**: Model predicts `<50K`, and that contradicts reality.\n",
        "\n",
        "**NOTE:** If desired, we can use the number of outcomes in each of these states to calculate secondary evaluation metrics, such as [precision and recall](https://developers.google.com/machine-learning/crash-course/classification/precision-and-recall)."
      ]
    },
    {
      "metadata": {
        "id": "nsUj_XZHU_mI",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Plot the Confusion Matrix\n",
        "\n",
        "The following cell define a function that uses the `sklearn.metrics.confusion_matrix` module to calculate all the instances (true positive, true negative, false positive, and false negative) needed to compute our binary confusion matrix and evaluation metrics."
      ]
    },
    {
      "metadata": {
        "id": "CmOWym53VITS",
        "colab_type": "code",
        "cellView": "form",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "#@test {\"output\": \"ignore\"}\n",
        "#@title Define Function to Compute Binary Confusion Matrix Evaluation Metrics\n",
        "def compute_eval_metrics(references, predictions):\n",
        "  tn, fp, fn, tp = confusion_matrix(references, predictions).ravel()\n",
        "  precision = tp / float(tp + fp)\n",
        "  recall = tp / float(tp + fn)\n",
        "  false_positive_rate = fp / float(fp + tn)\n",
        "  return precision, recall, false_positive_rate\n",
        "\n",
        "print('Binary confusion matrix and evaluation metrics defined.')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "ooYe_3lqTCPz",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "We will also need help plotting the binary confusion matrix. The function below combines various third-party modules (pandas DataFrame, Matplotlib, Seaborn) to draw the confusion matrix."
      ]
    },
    {
      "metadata": {
        "id": "TMIN_nl1VFuS",
        "colab_type": "code",
        "cellView": "form",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "#@title Define Function to Visualize Binary Confusion Matrix\n",
        "def plot_confusion_matrix(confusion_matrix, class_names, figsize = (8,6)):\n",
        "    # We're taking our calculated binary confusion matrix that's already in form \n",
        "    # of an array and turning it into a Pandas DataFrame because it's a lot \n",
        "    # easier to work with when visualizing a heat map in Seaborn.\n",
        "    df_cm = pd.DataFrame(\n",
        "        confusion_matrix, index=class_names, columns=class_names, \n",
        "    )\n",
        "    fig = plt.figure(figsize=figsize)\n",
        "    \n",
        "    # Combine the instance (numercial value) with its description\n",
        "    strings = np.asarray([['True Positives', 'False Negatives'],\n",
        "                          ['False Positives', 'True Negatives']])\n",
        "    labels = (np.asarray(\n",
        "        [\"{0:d}\\n{1}\".format(value, string) for string, value in zip(\n",
        "            strings.flatten(), confusion_matrix.flatten())])).reshape(2, 2)\n",
        "\n",
        "    heatmap = sns.heatmap(df_cm, annot=labels, fmt=\"\");\n",
        "    heatmap.yaxis.set_ticklabels(\n",
        "        heatmap.yaxis.get_ticklabels(), rotation=0, ha='right')\n",
        "    heatmap.xaxis.set_ticklabels(\n",
        "        heatmap.xaxis.get_ticklabels(), rotation=45, ha='right')\n",
        "    plt.ylabel('References')\n",
        "    plt.xlabel('Predictions')\n",
        "    return fig\n",
        "\n",
        "print('Binary confusion matrix visualization defined.')"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "hUvBYtwXVzlQ",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Now that we have all the necessary functions defined, we can now compute the binary confusion matrix and evaluation metrics using the outcomes from [our deep neural net model](#scrollTo=3nYSMg67jWaA). The output of this cell is a tabbed view, which allows us to toggle between the confusion matrix and evaluation metrics table."
      ]
    },
    {
      "metadata": {
        "id": "9enf_Jfi-AVS",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### FairAware Task #4\n",
        "\n",
        "Use the form below to generate confusion matrices for the two gender subgroups: `Female` and `Male`. Compare the number of False Positives and False Negatives for each subgroup. Are there any significant disparities in error rates that suggest the model performs better for one subgroup than another?"
      ]
    },
    {
      "metadata": {
        "id": "5TBzaWs1VKTa",
        "colab_type": "code",
        "cellView": "form",
        "colab": {}
      },
      "cell_type": "code",
      "source": [
        "#@title Visualize Binary Confusion Matrix and Compute Evaluation Metrics Per Subgroup\n",
        "CATEGORY  =  \"gender\" #@param {type:\"string\"}\n",
        "SUBGROUP =  \"Male\" #@param {type:\"string\"}\n",
        "\n",
        "# Given define subgroup, generate predictions and obtain its corresponding \n",
        "# ground truth.\n",
        "predictions_dict = single_task_deep_model.predict(input_fn=csv_to_pandas_input_fn(\n",
        "    test_df.loc[test_df[CATEGORY] == SUBGROUP], num_epochs=1, shuffle=False))\n",
        "predictions = []\n",
        "for prediction_item, in zip(predictions_dict):\n",
        "    predictions.append(prediction_item['class_ids'][0])\n",
        "actuals = list(\n",
        "    test_df.loc[test_df[CATEGORY] == SUBGROUP]['income_bracket'].apply(\n",
        "        lambda x: '>50K' in x).astype(int))\n",
        "classes = ['Over $50K', 'Less than $50K']\n",
        "\n",
        "# To stay consistent, we have to flip the confusion \n",
        "# matrix around on both axes because sklearn's confusion matrix module by\n",
        "# default is rotated.\n",
        "rotated_confusion_matrix = np.fliplr(confusion_matrix(actuals, predictions))\n",
        "rotated_confusion_matrix = np.flipud(rotated_confusion_matrix)\n",
        "\n",
        "tb = widgets.TabBar(['Confusion Matrix', 'Evaluation Metrics'], location='top')\n",
        "\n",
        "with tb.output_to('Confusion Matrix'):\n",
        "  plot_confusion_matrix(rotated_confusion_matrix, classes);\n",
        "\n",
        "with tb.output_to('Evaluation Metrics'):\n",
        "  grid = widgets.Grid(2,3)\n",
        "\n",
        "  p, r, fpr = compute_eval_metrics(actuals, predictions)\n",
        "\n",
        "  with grid.output_to(0, 0):\n",
        "    print('Precision ')\n",
        "  with grid.output_to(1, 0):\n",
        "    print(' %.4f ' % p)\n",
        "\n",
        "  with grid.output_to(0, 1):\n",
        "    print(' Recall ')\n",
        "  with grid.output_to(1, 1):\n",
        "    print(' %.4f ' % r)\n",
        "\n",
        "  with grid.output_to(0, 2):\n",
        "    print(' False Positive Rate ')\n",
        "  with grid.output_to(1, 2):\n",
        "    print(' %.4f ' % fpr)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "metadata": {
        "id": "TF3B5h3c-7Fb",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "### Solution\n",
        "\n",
        "Click below for some insights we uncovered"
      ]
    },
    {
      "metadata": {
        "id": "dhKR49AT_5ZK",
        "colab_type": "text"
      },
      "cell_type": "markdown",
      "source": [
        "Using default model parameters, you may find that the model performs better for male than female. Specifically, in our run, we found that both precision and recall for male (0.7490 and 0.4795, respectively) outperformed female (0.6787 and 0.3716, respectively).\n",
        "\n",
        "Hopefully going through this confusion matrix demonstration you find that the results varies slightly from the overall performance metrics, highlighting the importance of evaluating model performance across subgroup rather than in aggregate.\n",
        "\n",
        "In your work, make sure that you make a good decision about the tradeoffs between false positives, false negatives, true positives, and true negatives. For example, you may want a very low false positive rate, but a high true positive rate. Or you may want a high precision, but a low recall is okay.  \n",
        "\n",
        "**Choose your evaluation metrics in light of these desired tradeoffs.**"
      ]
    }
  ]
}
